/**
 * 用户信息，包含头部信息展示与退出管理
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var util = require("util");
    var ui = require("ui");
    require('permission');
    require("uploader");
    var environment = require('environment');

    var AuthorizeController = {
        init: function () {
            this._userInfo = null;
            this.bind();

            this._updateUserInfo();

            //无token时隐藏头部导航‘渠道管家’
            if (!util.getToken()) {
                $('#js_top_menu_nav').hide();
            }
        },
        bind: function () {
            $('#js_logout').on('click', $.proxy(this.logout, this));
            $('#js_change_pwd').on('click', $.proxy(this.openChangePwd, this));

            // 显示顶部下拉弹层
            var $menu;
            $("#js_system, #js_userinfo").on("click", function (e) {
                $menu = $(this).next();
                $menu.show();
                e.stopPropagation();
            });
            //点击桌面隐藏弹层
            $(document).click(function (e) {
                if ($menu) {
                    $menu.hide();
                    $menu = null;
                }
            });
        },
        /**
         * 退出登录，并跳转登录页面
         */
        logout: function () {
            $.ajax({
                url: environment.qmyx + G_CONFIG.api_prefix + "site/logout",
                dataType: 'jsonp',
                jsonp: 'callback',
                complete: function () {
                    util.goToLoginPage('');
                }
            })
        },
        openChangePwd: function () {
            require.async("dialogplus", function (dialog) {
                var dialogModel = dialog({
                    id: 'test',
                    title: "修改密码",
                    width: 420,
                    height: 250,
                    url: environment.qmyx + "/page/change_pwd.shtml",
                    onclose: function () {
                        //if(typeof callBack == "function"){
                        //    callBack.call(this,this.returnValue);
                        //}
                    }
                });
                dialogModel.showModal();
                window.closeChangePwdDialogSuccess = function () {
                    util.alert("修改成功!");
                    dialogModel.close();
                    dialogModel.remove();
                };
            });
        },
        changeLogo: function (imgPath) {
            $("#js_logo_upload_a").html("<img src='" + imgPath + "'>");
            util.myAjax({
                url: G_CONFIG.api_prefix + "site/save-logo-url",
                type: "get",
                data: {
                    url: imgPath
                },
                dataType: "json",
                success: function (data) {
                    if (data.retCode == "0") {
                        ui.showSucTip("上传成功");
                    }
                }
            });
        },
        /**
         * 获取用户信息
         * @returns {{userName:string}}
         */
        getUserInfo: function () {
            return this._userInfo;
        },
        _flushView: function () {
            $('#js_user_name').text(this._userInfo.userName);
            $('#js_org_name').text(this._userInfo.orgName);
            $('#js_token_name').text(this._userInfo.tokenName);
            if (this._userInfo.orgLogo) {
                $("#js_logo_wrap_a").html("<img src='" + this._userInfo.orgLogo + "'>");
                $("#js_logo_upload_a").html("<img src='" + this._userInfo.orgLogo + "'>");
            }
            if (this._userInfo.isAdmin && $('#js_logo_upload').length) {
                $("#js_logo_upload").show();
                $("#js_logo_wrap").hide();
                var callback = $.proxy(this.changeLogo);
                $('#js_logo_upload').fileupload({
                    dataType: 'json',
                    dropZone:$("#js_logo_upload"),
                    url: G_CONFIG["api_prefix"] + "common/file/upload-image",
                    add: function (e, data) {
                        data.submit();
                    },
                    done: function (e, data) {
                        var res = data.result;
                        if (res.retCode == "0") {
                            var img_url = res.data.path;
                            callback(img_url);
                        } else {
                            util.alert("上传失败:" + res.errMsg);
                        }
                    }
                });
                $('#js_logo_upload').on("click", function () {

                });
            }
        },

        /**
         * 获取用户信息
         */
        _updateUserInfo: function () {
            var userData = window['YKLoginData'];
            if (userData) {
                this._checkUserData(userData);

                window['YKLoginData'] = null;
            } else {
                var self = this;
                util.myAjax({
                    url: G_CONFIG.api_prefix + "site/login-data",
                    type: "get",
                    dataType: "json",
                    data: {
                        //NEED_TOKEN: false
                    },
                    success: function (res) {
                        self._checkUserData(res);
                    },
                    error: function () {
                        util.goToLoginPage();
                    }
                })
            }
        },
        /**
         * @param {Object} res
         */
        _checkUserData: function (res) {
            if (res['retCode'] == 0) {
                var data = res['data'];

                if (data['isGuest'] === false) {
                    this._userInfo = data;

                    this._flushView();
                } else {
                    util.goToLoginPage();
                }
            } else {
                util.goToLoginPage();
            }
        }
    };

    AuthorizeController.init();

    return AuthorizeController;
});